<template>
  <!-- 生产退料单 -->
  <div class="page-container">
    <div class="common-content-wrap">
      <TrTable
        ref="trTable"
        isNeedSelection
        v-model="searchParams"
        :searchShowList="searchShowList"
        :searchHideList="searchHideList"
        :btnList="btnList"
        :total="totalNum"
        :tableData="tableData"
        :tableColumn="tableColumn"
        :minSearchLabelWidth="86"
        requestName="searchHandle"
        @rowView="viewHandle"
        @print="printHandle"
        @export="exportHandle"
      />
    </div>
    <!-- 料号明细 -->
    <TrDetail
      v-model="isShowDetail"
      :leftList="detailList"
      statusModel="hidden"
      :detailData="detailData"
      :width="1227"
      :labelWidth="86"
      :isNeedFooter="false"
    >
      <template #table>
        <TrTable
          isPopup
          isNeedIndex
          :isNeedPagination="false"
          v-model="detailSearchParams"
          :tableData="detailTableData"
          :tableColumn="detailTableColumn"
          requestName="getBomListHandle"
          @rowView="rowDetailView"
        />
      </template>
    </TrDetail>
    <!-- 标签明细 -->
    <TrDetail
      v-model="isShowDetailMat"
      :leftList="detailListMat"
      statusModel="hidden"
      :detailData="detailDataMat"
      :width="1227"
      :isNeedFooter="false"
    >
      <template #tableMat>
        <TrTable
          isPopup
          isNeedIndex
          v-model="searchParamsMat"
          :tableData="tableDataMat"
          :total="totalMat"
          :tableColumn="tableColumnMat"
          requestName="getMatListHandle"
        />
      </template>
    </TrDetail>
    <div class="print-wrap" v-if="isShowPrint">
      <logPrint
        ref="print"
        title="生产退料单"
        :printDataList="printDataList"
        :basicConfig="basicConfig"
        :tableHeaderConfig="printHeaderConfig"
        :signConfig="printSignConfig"
      />
    </div>
  </div>
</template>

<script>
import {
  getList,
  getBillDetail,
  getBizDetail,
  getPrintData,
} from "@/api/logistics/productionReturnOrder.js";
import { getColor } from "@/utils/billColor";
import TrTable from "@/components/Tr-table/Tr-table.vue";
import TrDetail from "@/components/Tr-detail/Tr-detail.vue";
import logPrint from "./components/logPrint.vue";
export default {
  name: "produReturnOrder",
  components: {
    TrTable,
    TrDetail,
    logPrint,
  },
  data: () => ({
    isShowDetailMat: false,
    detailListMat: [
      {
        type: "text",
        id: 1,
        label: "基础信息",
        list: [
          {
            text: "原料料号",
            id: "materialCode",
            width: 33.33,
          },
          {
            text: "物料名称",
            id: "materialName",
            width: 33.33,
          },
          {
            text: "物料规格",
            id: "materialSpec",
            width: 33.33,
          },
          {
            text: "退料数量",
            id: "num",
            width: 33.33,
          },
          {
            text: "计量单位",
            id: "newNumUnit",
            width: 33.33,
          },
          {
            text: "退料重量",
            id: "weight",
            width: 33.33,
          },
          {
            text: "重量单位",
            id: "newWeightUnit",
            width: 33.33,
          },
          {
            text: "退料原因",
            id: "remark",
            width: 33.33,
          },
          {
            text: "退料仓库",
            id: "destWarehouseName",
            width: 33.33,
          },
        ],
      },
      {
        type: "slot",
        slotName: "tableMat",
        label: "标签明细",
      },
    ],
    detailDataMat: {},
    searchParamsMat: {
      current: 1,
      size: 10,
    },
    tableDataMat: [],
    totalMat: 0,
    tableColumnMat: [
      {
        type: "text",
        label: "物料标签",
        value: "barcode",
      },
      {
        type: "text",
        label: "数量",
        value: "num",
      },
      {
        type: "text",
        label: "计量单位",
        value: "newNumUnit",
      },
      {
        type: "text",
        label: "重量",
        value: "weight",
      },
      {
        type: "text",
        label: "重量单位",
        value: "newWeightUnit",
      },
    ],

    basicConfig: [
      [
        { label: "单号", prop: "billCode" },
        { label: "领料单号", prop: "relationBillCode" },
      ],
      [
        { label: "打印日期", prop: "printBizBillTime" },
        { label: "生产工单", prop: "workOrderCode" },
      ],
      [
        { label: "领料车间", prop: "destProdOrgName" },
        { label: "退料日期", prop: "createTime" },
      ],
      [{ label: "打印人员", prop: "printBizBillUserName" }],
    ],
    printHeaderConfig: [
      { label: "原料料号", prop: "materialCode" },
      { label: "物料名称", prop: "materialName" },
      { label: "物料规格", prop: "materialSpec" },
      { label: "退料地点", prop: "destWarehouseName" },
      { label: "退料原因", prop: "remark" },
      { label: "退料数量", prop: "num" },
      { label: "退料重量", prop: "weight" },
    ],
    printSignConfig: [
      { label: "生产确认", value: "" },
      { label: "仓管员", value: "" },
      { label: "制单人", value: "", prop: "createUserName" },
      { label: "品质", value: "" },
      { label: "审核人", value: "" },
    ],
    printDataList: [],
    detailSearchParams: {
      current: 1,
      size: 10,
    },
    detailTableColumn: [
      {
        type: "text",
        label: "原料料号",
        value: "materialCode",
      },
      {
        type: "text",
        label: "物料名称",
        value: "materialName",
      },
      {
        type: "text",
        label: "物料规格",
        value: "materialSpec",
      },
      {
        type: "text",
        label: "退料原因",
        value: "remark",
      },
      {
        type: "text",
        label: "退料仓库",
        value: "destWarehouseName",
      },
      {
        type: "text",
        label: "退料数量",
        value: "num",
      },
      {
        type: "text",
        label: "计量单位",
        value: "newNumUnit",
      },
      {
        type: "text",
        label: "退料重量",
        value: "weight",
      },
      {
        type: "text",
        label: "重量单位",
        value: "newWeightUnit",
      },
      {
        type: "option",
        label: "操作",
        fixed: "right",
        width: 80,
        showBtnList: [
          {
            label: "查看",
            option: "rowView",
          },
        ],
      },
    ],
    detailTableData: [],
    isShowDetail: false,
    detailList: [
      {
        type: "text",
        id: 1,
        label: "基础信息",
        list: [
          {
            text: "生产退料单",
            id: "billCode",
            width: 33.33,
          },
          {
            text: "状态",
            id: "stateName",
            width: 33.33,
          },
          {
            text: "领料单号",
            id: "relationBillCode",
            width: 33.33,
          },
          {
            text: "生产工单",
            id: "workOrderCode",
            width: 33.33,
          },
          {
            text: "创建人员",
            id: "createUserName",
            width: 33.33,
          },
          {
            text: "创建时间",
            id: "createTime",
            width: 33.33,
          },
          {
            text: "领料车间",
            id: "destProdOrgName",
            width: 33.33,
          },
          {
            text: "审核人员",
            id: "confirmUserName",
            width: 33.33,
          },
          {
            text: "审核时间",
            id: "confirmTime",
            width: 33.33,
          },
        ],
      },
      {
        type: "slot",
        slotName: "table",
        label: "单据明细",
        slotBottom: 32,
      },
    ],
    detailData: {},
    totalNum: 0,
    tableData: [],
    searchParams: {
      current: 1,
      size: 10,
      workOrderCode: "",
      materialCode: "",
      materialName: "",
      state: "",
    },
    searchShowList: [
      {
        isNeed: true,
        startStr: "createTimeStart",
        endStr: "createTimeEnd",
        id: "createTime",
        type: "daterange",
        width: 80,
        label: "创建时间",
        value: [],
        radio: 1,
        timePeriod: true,
      },
    ],
    searchHideList: [
      {
        label: "生产退料单",
        type: "input",
        width: 33.33,
        value: "",
        id: "billCode",
      },
      {
        label: "领料单号",
        type: "input",
        width: 33.33,
        value: "",
        id: "relationBillCode",
      },
      {
        id: "workOrderId",
        type: "loadselect",
        width: 33.33,
        label: "生产工单",
        value: "",
        requestObj: {
          url: "/api/mes-production-service/work-order/page",
          method: "post",
          searchKey: "workOrderCode",
          rlLabel: "workOrderCode",
          rlValue: "id",
          resultKey: "data,data,records",
        },
      },
      {
        id: "destProdOrgId",
        label: "领料车间",
        type: "loadselect",
        width: 33.33,
        value: "",
        list: [],
        selectedLabel: "",
        reviewLabel: "categoryName",
        requestObj: {
          url: "/api/trio-system/prod-org/page",
          method: "post",
          searchKey: "orgName",
          rlLabel: "orgName",
          rlValue: "id",
          resultKey: "data,data,records",
        },
        defaultParams: {
          orgLevelCode: "WORKSHOP",
        },
      },
      {
        label: "创建人员",
        type: "input",
        width: 33.33,
        value: "",
        id: "createUserName",
      },
      {
        label: "审核人员",
        type: "input",
        width: 33.33,
        value: "",
        id: "confirmUserName",
      },
      {
        label: "状态",
        type: "multiSelect",
        width: 33.33,
        value: "",
        list: [],
        id: "stateList",
      },
      {
        startStr: "confirmTimeStart",
        endStr: "confirmTimeEnd",
        id: "confirmTime",
        type: "daterange",
        width: 80,
        label: "审核时间",
        value: [],
        radio: -1,
        timePeriod: true,
      },
    ],
    btnList: [
      {
        label: "打印",
        option: "print",
        color: "blue",
        isRelaTable: true,
      },
      {
        label: "导出",
        option: "export",
        color: "white",
      },
    ],
    tableColumn: [
      {
        type: "text",
        label: "生产退料单",
        value: "billCode",
      },
      {
        type: "text",
        label: "状态",
        value: "stateName",
      },
      {
        type: "text",
        label: "领料单号",
        value: "relationBillCode",
      },
      {
        type: "text",
        label: "生产工单",
        value: "workOrderCode",
      },
      {
        type: "text",
        label: "领料车间",
        value: "destProdOrgName",
      },
      {
        type: "text",
        label: "创建人员",
        value: "createUserName",
      },
      {
        type: "text",
        label: "创建时间",
        value: "createTime",
      },
      {
        type: "text",
        label: "审核人员",
        value: "confirmUserName",
      },
      {
        type: "text",
        label: "审核时间",
        value: "confirmTime",
      },
      {
        type: "option",
        label: "操作",
        fixed: "right",
        width: 80,
        showBtnList: [
          {
            label: "查看",
            option: "rowView",
          },
        ],
      },
    ],
    detailRow: {},
    isShowPrint: false,
  }),
  computed: {
    ids() {
      return this.$refs.trTable.selectionList.map((item) => item.id);
    },
  },
  methods: {
    async printHandle() {
      await this.getPrintData();
      this.isShowPrint = false;
      await this.$textShow({
        title: this.$t("tip.label"),
        content: ["是否确认打印？"],
      });
      this.isShowPrint = true;

      this.$nextTick(() => {
        this.$refs.print.printHandle();
        this.$refs.trTable.clearSelect();
      });
    },
    async getPrintData() {
      const printDataList = await Promise.all(
        this.ids.map(async (id) => {
          const axiosObj = {
            bizBillId: id,
            current: 1,
            size: 2000,
          };
          const { data: res } = await getPrintData(axiosObj);
          return res;
        })
      );
      this.$validateData(printDataList);
      this.setPrintDataList(printDataList);
    },
    setPrintDataList(resList) {
      this.printDataList = resList.map((item) => {
        const { data } = item;
        this.printSignConfig.forEach((item) => {
          if (!item.prop) return;
          item.value = data[item.prop];
        });
        return {
          ...data,
          qrCode: data.billCode,
          tableData: data.bizDetailDetailList.map((i) => {
            return {
              ...i,
              num: `${i.num}${i.numUnitCode}`,
              weight: `${i.weight}${i.weightUnitCode}`,
            };
          }),
        };
      });
    },
    async viewHandle(row) {
      const axiosObj = {
        ...this.detailSearchParams,
        bizBillId: row.id,
      };
      const { data: res } = await getBillDetail(axiosObj);
      this.$validateData(res);

      this.setDetailData(res.data);
      this.detailTableData = res.data.bizDetailDetailList;
      this.detailTableData.forEach((item) => {
        item.newNumUnit = `${item.numUnitCode}(${item.numUnitName})`;
        item.newWeightUnit = `${item.weightUnitCode}(${item.weightUnitName})`;
      });
      this.isShowDetail = true;
    },
    setDetailData(data) {
      const statusNameObj = this.$findByProperty(
        this.detailList,
        "id",
        "stateName",
        "list"
      );
      if (statusNameObj) statusNameObj.valueColor = getColor("DF", data.state);

      this.detailData = data;
    },
    exportHandle() {
      this.$exportHandle({ vm: this, params: this.searchParams });
    },
    getBomListHandle() {},
    async getListHandle() {
      const axiosObj = {
        ...this.searchParams,
        dataSource: 10,
      };
      const { data: res } = await getList(axiosObj);
      this.$validateData(res.data.records);
      res.data.records.forEach((item) => {
        item["stateNameColor"] = getColor("DF", item.state);
      });
      this.tableData = res.data.records;
      this.totalNum = res.data.total;
    },
    searchHandle() {
      this.getListHandle();
    },
    async rowDetailView(row) {
      this.detailRow = row;
      this.getMatListHandle();
      this.isShowDetailMat = true;
    },
    async getMatListHandle() {
      const axiosObj = {
        ...this.detailSearchParams,
        bizDetailId: this.detailRow.bizDetailId,
      };
      const { data: res } = await getBizDetail(axiosObj);
      this.$validateData(res);
      this.detailDataMat = {
        ...res.data,
        newNumUnit: `${res.data.numUnitCode}(${res.data.numUnitName})`,
        newWeightUnit: `${res.data.weightUnitCode}(${res.data.weightUnitName})`,
      };

      this.setTableDataMat(res.data.billBarcodePageList);
    },
    setTableDataMat(res) {
      this.tableDataMat = res.records.map((item) => {
        return {
          ...item,
          newNumUnit: `${item.numUnitCode}(${item.numUnitName})`,
          newWeightUnit: `${item.weightUnitCode}(${item.weightUnitName})`,
        };
      });
      this.totalMat = res.total;
    },
    getSum(list) {
      return list.reduce(
        (acc, item) => {
          const usableNum =
            typeof item.usableNum === "number"
              ? item.usableNum
              : parseFloat(item.usableNum);
          const usableWeight =
            typeof item.usableWeight === "number"
              ? item.usableWeight
              : parseFloat(item.usableWeight);

          if (!isNaN(usableNum)) {
            acc.numSum += usableNum;
          }
          if (!isNaN(usableWeight)) {
            acc.weightSum += usableWeight;
          }

          return acc;
        },
        { numSum: 0, weightSum: 0 }
      );
    },
    async initHandle() {
      const res = await this.$fetchEnumApi("mes-warehouse-service", [
        "RefundBizBillStateEnum",
      ]);
      const list = res["RefundBizBillStateEnum"];
      const stateListObj = this.$findByProperty(
        this.searchHideList,
        "id",
        "stateList"
      );
      stateListObj && (stateListObj.list = list);
    },
  },
  async mounted() {
    this.initHandle();

    // this.getListHandle();
  },
};
</script>

<style lang="scss" scoped>
.print-wrap {
  position: fixed;
  width: 100vw;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: -999;
  opacity: 0;
}
</style>
